<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="108px">
      <el-form-item label="生产工单编码" prop="workorderCode">
        <el-input v-model="queryParams.workorderCode" placeholder="请输入生产工单编码" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="退料开始时间" prop="backStartTime">
        <el-date-picker clearable v-model="queryParams.backStartTime" type="date" value-format="yyyy-MM-dd" placeholder="请选择退料开始时间"></el-date-picker>
      </el-form-item>
      <el-form-item label="退料结束时间" prop="backEndTime">
        <el-date-picker clearable v-model="queryParams.backEndTime" type="date" value-format="yyyy-MM-dd" placeholder="请选择退料结束时间"></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!-- 2024-12-29 djj 去掉 新增 按钮 -->
      <!--  <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="manageQuery({},'生产退料','add')"
          v-hasPermi="['system:back:add']"
        >新增</el-button>
      </el-col> -->
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:back:edit']"
        >修改</el-button>
      </el-col>-->
      <!-- <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:back:remove']"
        >删除</el-button>
      </el-col> -->
      <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:back:export']"
        >导出</el-button>
      </el-col> -->
      <!-- <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar> -->
    </el-row>

    <el-table v-loading="loading" :data="backList" @selection-change="handleSelectionChange" height="calc(100vh - 300px)">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" width="50px">
        <template slot-scope="scope">
          <span>{{ scope.$index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="退料编码" align="center" prop="backCode">
        <template slot-scope="scope">
          <el-link type="primary" style="font-size:12px;vertical-align: baseline;" @click="handleCheck(scope.row)">{{
            scope.row.backCode }}</el-link>
        </template>
      </el-table-column>
      <el-table-column label="生产工单" align="center" prop="workorderCode" />
      <!-- <el-table-column label="审核状态" align="center" prop="backStatus" /> -->
      <el-table-column label="状态" align="center" prop="returnStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.rejection_status" :value="scope.row.returnStatus" />
        </template>
      </el-table-column>
      <!-- <el-table-column label="备注" align="center" prop="remark" /> -->
      <el-table-column label="退料人" align="center" prop="backUser" />
      <el-table-column label="退料时间" align="center" prop="backTime" width="180">
      </el-table-column>
      <!-- <el-table-column label="审核人" align="center" prop="checkUser" /> -->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <!--           -->
          <span v-if="scope.row.returnStatus == 1 || scope.row.returnStatus == 7">
            <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate2(scope.row)" v-hasPermi="['produce:materialReturn:edit']">修改</el-button>
          </span>
          <span v-if="scope.row.returnStatus == 1">
            <el-button size="mini" type="text" icon="el-icon-delete" @click="manageQuery(scope.row, '生产退料', 'del')" v-hasPermi="['produce:materialReturn:remove']">删除</el-button>
            <el-button size="mini" type="text" icon="el-icon-edit" v-hasPermi="['produce:checkOrder:create']" @click="manageQuery(scope.row, '生产退料', 'quality')">生成质检单</el-button>
          </span>
          <el-button size="mini" type="text" @click="giveData(scope.row)" v-else v-hasPermi="['produce:materialReturn:print']">打印退料单</el-button>
          <!-- add begin by zyj 2024/11/23 -->
          <el-button size="mini" type="text" v-if="scope.row.returnStatus == '5'" icon="el-icon-edit" v-hasPermi="['produce:inboundOrder:create']" @click="generateStockInOrder(scope.row, '生产退料', 'quality')">生成入库单</el-button>
          <el-button size="mini" type="text" v-if="scope.row.toErpStatus == '0'&&scope.row.returnStatus == '3'" icon="el-icon-edit" v-hasPermi="['mes:k3cloud:productionBack:saveToErp']" @click="saveToErp(scope.row)">上传ERP</el-button>
          <!-- add end by zyj 2024/11/23 -->

          <!-- <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleCheckDetail(scope.row,'1')"
            v-hasPermi="['system:back:edit']"
            v-if="scope.row.backStatus==1"
          >创建审批流</el-button> -->
          <!-- <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleMeterial(scope.row)"
            v-hasPermi="['system:supply:approval']"
            v-if="scope.row.backStatus==3"
          >生成退料单</el-button> -->

          <!-- <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleCheckDetail(scope.row,'2')"
            v-hasPermi="['system:supply:approval']"
            v-if="scope.row.isExamine==0 "
          >审批</el-button> -->
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" :page-sizes="[10, 50, 100, 200, 300, 400, 500]" />

    <!-- 添加或修改生产退料单基础对话框 -->
    <div v-if="open">
      <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
        <el-form ref="form" :model="form" :rules="rules" label-width="100px">
          <el-tag size="large" style="font-size: 20px;">基本信息</el-tag>
          <hr />
          <el-row>
            <el-col :span="12">
              <div style="display: flex;">
                <el-input v-model="form.backCode" placeholder="请输入退料编码" v-if="optType === 'add'" style="flex:1;" />
                <span v-if="optType === 'update' || optType === 'check'">{{ form.backCode }}</span>
                <el-switch v-model="autoGenFlag" active-color="#13ce66" active-text="自动生成" @change="handleAutoGenChange(autoGenFlag)" v-if="optType !== 'update' && optType !== 'check'"></el-switch>
              </div>
            </el-col>
            <el-col :span="12">
              <el-switch v-model="autoGenFlag" active-color="#13ce66" active-text="自动生成" @change="handleAutoGenChange(autoGenFlag)" v-if="optType !== 'update' && optType !== 'check'"></el-switch>
            </el-col>
            <el-col :span="12">
              <el-form-item label="生产工单id" prop="workorderId">
                <el-input v-model="form.workorderId" placeholder="请输入生产工单id" @keyup.enter.native="handleGetSN" v-if="optType !== 'check'" style="width: 220px;" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="生产工单" prop="workorderCode">
                <el-input v-model="form.workorderCode" disabled style="width: 220px;" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="退料原因" prop="reasonVal">
                <el-select style="width: 220px;" clearable v-model="form.reasonVal" placeholder="请选择退料原因" v-if="optType !== 'check'">
                  <el-option v-for="(item, index) of dictList" :key="index" :label="item.dictLabel" :value="item.dictValue">{{ item.dictLabel }}</el-option>
                </el-select>
                <span v-if="optType === 'check'">
                  <dict-tag :options="dict.type.mes_material_back_reason" :value="form.reasonVal" />
                </span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="扫码" prop="materialSerial" v-if="optType !== 'check'">
                <el-autocomplete clearable style="width: 360px;" class="inline-input" v-model="form.materialSerial" :fetch-suggestions="querySearch" placeholder="扫码" :disabled="optType == 'check'" value-key="sequenceCode" label-key="sequenceCode" @select="handleSelect">
                  <template slot-scope="{ item }">
                    <span>{{ item.sequenceCode }}</span>
                  </template>
                </el-autocomplete>
                <el-button type="primary" @click="querySnCodeInfo" style="margin-left: 30px;">查询</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div v-if="personList.length > 0">
          <el-tag size="large" style="font-size: 20px;">审批流信息</el-tag>
          <hr />
        </div>
        <el-steps :active="stepResult == 'REFUSE' ? activeStep : activeStep" align-center>
          <el-step v-for="item in personList" :key="item.userMobile" :title="item.userNickname" :description="item.resultName" :status="item.result == 'REFUSE' ? 'error' : ''"></el-step>
        </el-steps>
        <el-tag size="large" style="font-size: 20px;">物料信息</el-tag>
        <hr />
        <!-- <el-tabs type="border-card" >
        <el-tab-pane label="详情">-->
        <back-detail ref="backDetail" @onSelected="onSelected" :optType="optType" :parentCode="parentCode" :parentId="parentId"></back-detail>
        <!-- </el-tab-pane>
        </el-tabs>-->

        <div slot="footer" class="dialog-footer" v-if="optType !== 'check'">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>
    </div>
    <BackDetails ref="backDetails" @onSelected="onSelected" :backId="parentId"></BackDetails>
    <BackCheck ref="backCheck" @onSelected="onSelected" :backId="parentId" :checkType="checkType"></BackCheck>
    <PrintChild v-if="openPrint" ref="printchild"></PrintChild>
    <!-- 2024-12-29 djj 新增 修改弹出框 -->
    <Edit ref="edit" @onSelected="onSelected"></Edit>
  </div>
</template>

<script>
import {
  listBack,
  getBack,
  delBack,
  addBack,
  updateBack,
  addBatchBackInfo,
  updateBatchBackInfo,
  getBackApprovalProcess,
  getApprovalInfo,
  getApprovalList,
  getWareHouseList,
  getBackResonList,
  backProcess,
  getBackCreateProcess,
  backGenerate,
  getSequenceCodeByWorkorderCode,
  generateStockInOrder,
  saveToErp
} from "@/api/mes/pro/productBack";
// 按钮权限
import {
  selectUserRole,
} from "@/api/mes/pro/workorder";
import backDetail from "./backDetail.vue";
import BackDetails from "./detail.vue";
import BackCheck from "./backCheck.vue";
import PrintChild from "./print/print.vue";
import Edit from "./components/edit.vue";
import { genCode } from "@/api/mes/md/rule";
import redirectVue from '../../../redirect.vue';
export default {
  name: "Back",
  dicts: ["mes_material_back_reason", 'rejection_status'],
  components: { backDetail, BackDetails, BackCheck, PrintChild, Edit },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 生产退料单基础表格数据
      backList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        backCode: null,
        backStatus: null,
        workorderCode: null,
        checkUser: null,
        checkTime: null,
        backUser: null,
        backStartTime: null,
        backEndTime: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      optType: null,
      parentCode: "",
      selectedRows: null,
      autoGenFlag: false,
      parentId: "",
      //审批人
      personList: [],
      //处于哪个环节
      activeStep: null,
      stepResult: null,
      dictList: [],
      checkType: null,
      openPrint: false,
      snList: [],
      selectSequenceCode: null,
    };
  },
  created() {
    this.getList();
  },
  watch: {
    selectedRows: {
      // 每个属性值发生变化就会调用这个函数
      handler(newVal, oldVal) {
        console.log('oldVal-selectedRows:', oldVal)
        console.log('newVal-selectedRows:', newVal)
        this.snList = this.snList.filter(item => {
          return !(newVal.some(element => element.materialSerial === item.sequenceCode))
        })
      },
      // 立即处理 进入页面就触发
      immediate: true,
    },
  },


  methods: {
    //回写erp
    saveToErp(data) {
      this.loading = true
      saveToErp(data.backCode).then(msg => {
        if (msg.code == 200) {
          this.$modal.msgSuccess("操作成功");
          this.getList();
        } else {
          this.loading = false
        }
      }).catch(erro => {
        this.loading = false
      })
    },
    //add begin by zyj 2024/11/23
    generateStockInOrder(row) {
      this.$confirm('确定要生成生产入库单？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return generateStockInOrder({ id: row.id });
      }).catch(() => { }).then(res => {
        if (res && res.code == 200) {
          this.$modal.msgSuccess("新增成功");
          this.getList();
        }

      })
    },
    //add end by zyj 2024/11/23
    querySearch(queryString, cb) {
      var snList = this.snList;
      var results = queryString ? snList.filter(this.createStateFilter(queryString)) : snList;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createStateFilter(queryString) {
      return (state) => {
        return state.sequenceCode.includes(queryString);
      };
    },
    handleSelect(item) {
      this.selectSequenceCode = item.sequenceCode
      console.log(111, item)
    },
    handleGetSN() {
      getSequenceCodeByWorkorderCode(this.form.workorderId).then(res => {
        console.log(res)
        this.form.workorderCode = res.data.workorderCode
        const arr = res.data.sequenceCode ? res.data.sequenceCode : []
        const newArr = arr.map(item => {
          const obj = {
            sequenceCode: item
          }
          return obj
        })
        this.snList = newArr.filter(item => {
          return !(this.selectedRows.some(element => element.materialSerial === item.sequenceCode))
        })
      })
    },
    /** 查询生产退料单基础列表 */
    getList() {
      this.loading = true;
      listBack(this.queryParams).then(response => {
        this.backList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
      // getWareHouseList({}).then(response => {
      //   this.warehouseList = response.data;
      // });
      // getBackResonList().then(response => {
      //   this.dictList = response.data;
      //   // this.dictList.forEach((val, key) => {
      //   //   val.dictValue = Number(val.dictValue);
      //   // });
      // });
    },
    giveData(row) {
      this.openPrint = true
      this.$nextTick(() => {
        this.$refs.printchild.init(row);
      })
    },
    onSelected(selectedRows) {
      this.selectedRows = selectedRows;
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    querySnCodeInfo() {
      if (this.form.workorderCode && this.form.materialSerial) {
        this.parentCode = this.form.materialSerial;
        // let flag = false
        // this.snList.forEach(item => {
        //   if(item.issueCode === this.form.materialSerial){
        //     flag = true
        //   }
        // })
        // if(flag){
        //   this.form.materialSerial = this.selectSequenceCode
        // }
        const obj = {
          ...this.form
        }
        this.form.materialSerial = null
        this.$refs.backDetail.refreshBackList(obj);
      } else {
        this.$modal.msgError("请输入工单编号和序列号！！");
      }
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        backCode: null,
        backStatus: null,
        workorderCode: null,
        checkUser: null,
        checkTime: null,
        backUser: null,
        backTime: null,
        remark: null,
        materialSerial: null,
        processInstanceId: null,
        reasonVal: null,
        workorderId: null
      };
      this.personList = [];
      this.activeStep = null;
      this.stepResult = null;
      this.resetForm("form");
      this.autoGenFlag = false;
      this.parentCode = "";
      this.optType = null;
      this.selectedRows = [];
      this.parentId = null;
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加生产退料单";
      this.optType = "add";
    },
    /* 2024-12-29 重写修改按钮 */
    handleUpdate2(row) {
      const id = row.id || this.ids;
      this.parentId = id;
      this.optType = "update";
      this.$refs.edit.init(row);
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      this.optType = "update";
      this.parentId = id;
      getBack(id).then(response => {
        this.form = response.data;
        // this.form.reasonVal = this.form.reasonVal);
        this.handleGetSN()
        this.open = true;
        this.title = "修改生产退料单";
      });
    },
    /** 生成生产退料单审批流 */
    handleProcess(row) {
      this.reset();
      const id = row.id || this.ids;
      // getBackApprovalProcess(id).then(response => {
      //   this.$modal.msgSuccess("创建生产退料单审批流成功");
      //   this.getList();
      // });
      getBackCreateProcess(id).then(response => {
        this.$modal.msgSuccess("创建生产退料单审批流成功");
        this.getList();
      });
    },
    /** 查看详情按钮操作 */
    handleCheck(row) {
      this.reset();
      // const id = row.id || this.ids
      // this.optType='check';
      // this.parentId=id;
      this.parentId = row.id;

      this.$refs.backDetails.showFlag = true;
      console.log(this.parentId, this.$refs.backDetails.showFlag);
      // getBack(id).then(response => {
      //   this.form = response.data;
      //   this.open = true;
      //   this.title = "生产退料单详情";
      //   if(this.form.processInstanceId!=undefined&&this.form.processInstanceId!=null){
      //     getApprovalList(id).then(response => {
      //      this.personList=response.data.personList;
      //      for(const key in this.personList){
      //         if(this.personList[key].result!=undefined){
      //           if(this.personList[key].result=='AGREE'){
      //             this.personList[key].resultName='同意'
      //           }
      //           else if(this.personList[key].result=='REFUSE'){
      //             this.personList[key].resultName='拒绝'
      //           }
      //         }

      //       }
      //      this.activeStep=response.data.step;
      //      this.stepResult=response.data.supplyResult;
      //   });
      //   }

      // });
    },
    /** 提交按钮 */
    submitForm() {
      if (this.selectedRows == null || this.selectedRows.size == 0) {
        this.$notify({
          title: "提示",
          type: "warning",
          message: "请至少选择一条数据!"
        });
        return;
      }
      this.$refs["form"].validate(valid => {
        if (valid) {
          let reqParam = {
            baseInfo: this.form,
            detailList: this.selectedRows
          };
          if (this.form.id != null) {
            updateBatchBackInfo(reqParam).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addBatchBackInfo(reqParam).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除生产退料单基础编号为"' + ids + '"的数据项？')
        .then(function () {
          return delBack(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/back/export",
        {
          ...this.queryParams
        },
        `back_${new Date().getTime()}.xlsx`
      );
    },
    handleAutoGenChange(autoGenFlag) {
      if (autoGenFlag) {
        genCode("MATERIAL_BACK").then(response => {
          this.form.backCode = response;
        });
      } else {
        this.form.backCode = null;
      }
    },
    // 生成生产退料单
    handleMeterial(row) {
      const params = {
        processInstanceId: row.processInstanceId
      };
      this.$modal
        .confirm(
          '是否确认生产退料单编码为"' +
          row.supplyCode +
          '"的数据项生成生产退料单！！！'
        )
        .then(function () {
          return backProcess(params);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("生成成功");
        })
        .catch(() => { });
    },
    // 审核
    handleCheckDetail(row, type) {
      this.parentId = row.id;
      this.checkType = type;
      console.log(this.parentId);
      this.$refs.backCheck.showFlag = true;
    },
    //生成iqc质检单
    handleGenerate(row) {
      this.$modal
        .confirm('是否确认生产退料单基础编号为"' + row.backCode + '"的数据项生成质检单？')
        .then(function () {
          return backGenerate(row.id);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("生成成功");
        }).catch(() => { });
      // backGenerate(row.id).then(res=>{
      //   console.log(res,'生成质检单的res');
      //   if(res.code == 200){
      //     this.$modal.msgSuccess("生成成功");
      //   }
      // })
    },
    // manage
    manageQuery(row, name, type) {
      selectUserRole(name).then((res) => {
        if (type == 'add') {
          this.handleAdd()
        } else if (type == 'edit') {
          this.handleUpdate(row)
        } else if (type == 'del') {
          this.handleDelete(row)
        } else if (type == 'quality') {
          this.handleGenerate(row)
        }

      }).catch(() => {
        //  this.$modal.msgError("此用户暂时没有权限");
        return "false"
      });
    },
  }
};
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
.app-container ::v-deep .el-drawer__header > :first-child {
  font-weight: 700 !important;
  font-size: 20px;
}

.tabsDiv {
  padding: 20px;
  padding-top: 0;
}

.tabsDiv ::v-deep .el-tabs--card > .el-tabs__header .el-tabs__item {
  font-weight: 700;
  font-size: 18px;
}

.drawerFooter {
  text-align: right;
  padding: 20px;
}

.bg-purple {
  display: flex;
  align-items: center;

  span:nth-child(1) {
    display: inline-block;
    width: 110px;
    white-space: nowrap;
    line-height: 30px;
  }
}

.dialog-footer {
  padding-top: 20px;
  text-align: center;
}

.app-container ::v-deep .el-drawer__header {
  padding-top: 10px !important;
  padding-bottom: 5px !important;
  margin-bottom: 10px !important;
}
</style>
